﻿using System;
using System.Data;
using System.Text;
using System.Collections.Generic;
using HF.Framework.DataClientDBAgent;
using HF.WorkFlow.DataContract;
using HF.Framework.SqlDataContract;
namespace HF.Forms.Data
{
    /// <summary>
    /// 数据访问类ChildForm。
    /// </summary>
    public class ChildForm
    {
        #region  私有字段
        private SqlDataItem sqlDataItem = new SqlDataItem();
        private string[] fieldList = { "ChildFormId", "Caption", "FilePath", "FileName", "Description", "FormType"};
        private string tableName = "HF_ChildForms";
        private string keyField = "ChildFormId";
        private string sqlString = "";

        #endregion

        #region  私有方法
        private void setParameter(ChildFormEntity entity)
        {
            sqlDataItem.ParameterList.Clear();
            sqlDataItem.AppendParameter("@ChildFormId", entity.ChildFormId, typeof(string));
            sqlDataItem.AppendParameter("@Caption", entity.Caption, typeof(string));
            sqlDataItem.AppendParameter("@FilePath", entity.FilePath, typeof(string));
            sqlDataItem.AppendParameter("@FileName", entity.FileName, typeof(string));
            sqlDataItem.AppendParameter("@Description", entity.Description, typeof(string));
            sqlDataItem.AppendParameter("@FormType", entity.FormType, typeof(string));
        }

        private void setInsertSql()
        {
            string tmpValueList = "";
            string tmpFieldName = "";
            sqlString = "insert into " + tableName + "(";
            int tmpInt = this.fieldList.Length;
            for (int i = 0; i < tmpInt - 1; i++)
            {
                tmpFieldName = fieldList[i].ToString();
                sqlString = sqlString + tmpFieldName + ", ";
                tmpValueList = tmpValueList + "@" + tmpFieldName + ",";
            }
            tmpFieldName = this.fieldList[tmpInt - 1].ToString();
            sqlString = sqlString + tmpFieldName;
            tmpValueList = tmpValueList + "@" + tmpFieldName;
            this.sqlString = sqlString + ")values(" + tmpValueList + ")";
            sqlDataItem.CommandText = sqlString;
        }

        private void setUpdateSql()
        {
            string tmpFieldName = "";
            int tmpInt = this.fieldList.Length;
            sqlString = "update " + tableName + " set ";
            for (int i = 0; i < tmpInt - 1; i++)
            {
                tmpFieldName = fieldList[i].ToString();
                sqlString = sqlString + tmpFieldName + " = @" + tmpFieldName + ", ";
            }
            tmpFieldName = this.fieldList[tmpInt - 1].ToString();
            sqlString = sqlString + tmpFieldName + " = @" + tmpFieldName;
            sqlString = sqlString + " where " + keyField + "=@" + this.keyField;
            sqlDataItem.CommandText = sqlString;
        }

        public ChildFormEntity GetChildFormEntity(DataRow dr)
        {
            ChildFormEntity entity = new ChildFormEntity();
            string value = "";
            entity.ChildFormId = dr["ChildFormId"].ToString();
            entity.Caption = dr["Caption"].ToString();
            entity.FilePath = dr["FilePath"].ToString();
            entity.FileName = dr["FileName"].ToString();
            entity.Description = dr["Description"].ToString();
            entity.FormType = dr["FormType"].ToString();
            return entity;
        }

        #endregion

        #region  构造函数
        public ChildForm()
        { }
        public static ChildForm GetInstance()
        {
            return new ChildForm();
        }
        #endregion

        #region  公有方法
        #region  基本方法
        /// <summary>
        /// 增加
        /// </summary>
        /// <param name="entity">数据实体</param>
        /// <returns>影响的记录条数</returns>
        public int Insert(ChildFormEntity entity)
        {
            try
            {
                setInsertSql();//设定insert语句
                setParameter(entity);//设定参数
                ClientDBAgent agent = new ClientDBAgent();
                return agent.ExecuteNonQuery(sqlDataItem);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="entity">数据实体</param>
        /// <returns>影响的记录条数</returns>
        public int Update(ChildFormEntity entity)
        {
            try
            {
                setUpdateSql();//设定insert语句
                setParameter(entity);//设定参数
                ClientDBAgent agent = new ClientDBAgent();
                return agent.ExecuteNonQuery(sqlDataItem);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 是否存在该记录
        /// </summary>
        public bool Exists(string childFormId)
        {
            string tmpSql = "select * from " + tableName + " where " + keyField + "=@" + keyField;
            SqlDataItem sqlItem = new SqlDataItem();
            sqlItem.CommandText = tmpSql;
            sqlItem.AppendParameter("@" + keyField, childFormId);
            ClientDBAgent agent = new ClientDBAgent();
            return agent.RecordExists(sqlItem);
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="childFormId">主键Id</param>
        /// <returns>影响的记录条数</returns>
        public void Delete(string childFormId)
        {
            try
            {
                string tmpSql = "delete from " + tableName + " where  " + keyField + "=@" + keyField;
                SqlDataItem sqlItem = new SqlDataItem();
                sqlItem.CommandText = tmpSql;
                sqlItem.AppendParameter("@" + keyField, childFormId);
                ClientDBAgent agent = new ClientDBAgent();
                agent.ExecuteNonQuery(sqlItem);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 获取一条数据记录
        /// </summary>
        /// <param name="ChildFormId">主键Id</param>
        /// <returns>DataTable</returns>
        public DataTable GetChildFormTable(string childFormId)
        {
            string tmpSql = "select * from " + tableName + " where " + keyField + "=@" + keyField;
            try
            {
                SqlDataItem sqlItem = new SqlDataItem();
                sqlItem.CommandText = tmpSql;
                sqlItem.AppendParameter("@" + keyField, childFormId);
                ClientDBAgent agent = new ClientDBAgent();
                return agent.ExecuteDataTable(sqlItem);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 获取一个数据实体
        /// </summary>
        /// <param name="childFormId">主键Id</param>
        /// <returns>DataTable</returns>
        public ChildFormEntity GetChildFormEntity(string childFormId)
        {
            DataTable dt = GetChildFormTable(childFormId);
            if (dt != null && dt.Rows.Count > 0)
            {
                return GetChildFormEntity(dt.Rows[0]);
            }
            return null;
        }

        #endregion

        #region  扩展方法
        //此处添加扩展方法

        /// <summary>
        /// 删除子表单隶属的主表单关系
        /// </summary>
        /// <param name="childFormId"></param>
        /// <returns>是否成功</returns>
        public  bool RemoveFromMainForm(string childFormId)
        {

            try
            {
                string sqlStr = "delete from HF_MainChildForm where ChildFormId=@ChildFormId";
                SqlDataItem sqlItem = new SqlDataItem();
                sqlItem.CommandText = sqlStr;
                sqlItem.AppendParameter("@ChildFormId", childFormId);
                ClientDBAgent agent = new ClientDBAgent();
                agent.ExecuteNonQuery(sqlItem);
                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 获取所有子表单
        /// </summary>
        /// <param name="table"></param>
        /// <returns></returns>          --zhuyun  20120429
        public DataTable GetFormTable(string mainformid)
        {
            try
            {
                string sql = "select FormID,MasterTableName,DetailsJson,0 as MasterTableNameType from dbo.SysCustomDefineForm WHERE cast(FormID as Varchar(50)) IN(select FilePath from HF_ChildForms where ChildFormId in" +
                   "(select ChildFormId from HF_MainChildForm where MainFormId=@MainformId))";
                SqlDataItem sqlItem = new SqlDataItem();
                sqlItem.CommandText = sql;
                sqlItem.AppendParameter("@MainformId", mainformid);
                ClientDBAgent agent = new ClientDBAgent();
                return agent.ExecuteDataTable(sqlItem);

            }
            catch (Exception)
            {
                
                throw;
            }
        }


        /// <summary>
        /// 获得所有子表单
        /// </summary>
        /// <returns>DataTable</returns>
        public  DataTable GetAllChildForms()
        {
            try
            {
                string tmpStr = "select * from HF_ChildForms order by Caption";
                SqlDataItem sqlItem = new SqlDataItem();
                sqlItem.CommandText = tmpStr;
                ClientDBAgent agent = new ClientDBAgent();
                return agent.ExecuteDataTable(sqlItem);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 获得所有子表单
        /// </summary>
        /// <returns>DataTable</returns>
        public List<ChildFormEntity> GetAllChildFormEntitys()
        {
            List<ChildFormEntity> result = new List<ChildFormEntity>();
            DataTable dt = GetAllChildForms();
            try
            {
                foreach (DataRow dr in dt.Rows)
                {
                    ChildFormEntity entity = GetChildFormEntity(dr);
                    result.Add(entity);
                }
                return result;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 获得主表单的所有子表单列表
        /// </summary>
        /// <param name="mainFormId">主表单Id</param>
        /// <returns>子表单table</returns>
        public DataTable GetChildFormsOfMain(string mainFormId)
        {
            try
            {
                string tmpStr = " select c.* from HF_MainChildForm m left join HF_ChildForms c on c.ChildformId=m.ChildFormId "+
                                " where m.MainFormId=@mainFormId order by FormOrder";
                SqlDataItem sqlItem = new SqlDataItem();
                sqlItem.CommandText = tmpStr;
                sqlItem.AppendParameter("@mainFormId", mainFormId);
                ClientDBAgent agent = new ClientDBAgent();
                return agent.ExecuteDataTable(sqlItem);

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 获得主表单的所有子表单列表
        /// </summary>
        /// <param name="mainFormId">主表单Id</param>
        /// <returns>Entitys</returns>
        public List<ChildFormEntity> GetChildFormEntitysOfMain(string mainFormId)
        {
            List<ChildFormEntity> result = new List<ChildFormEntity>();
            DataTable dt = GetChildFormsOfMain(mainFormId);
            try
            {
                foreach (DataRow dr in dt.Rows)
                {
                    ChildFormEntity entity = GetChildFormEntity(dr);
                    result.Add(entity);
                }
                return result;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 获得流程所有子表单信息
        /// </summary>
        /// <param name="workFlowId">流程Id</param>
        /// <returns>DataTable</returns>
        public DataTable GetChildFormsOfWorkFlow(string workFlowId)
        {
            try
            {
                string tmpStr = "select distinct cf.* from HF_WorkTaskForm wtf left join HF_MainChildForm wcf on wtf.MainFormId=wcf.MainFormId " +
                                " left join HF_ChildForms cf on cf.ChildFormId=wcf.ChildFormId " +
                                "         where wtf.workflowid=@workFlowId ";

                SqlDataItem sqlItem = new SqlDataItem();
                sqlItem.CommandText = tmpStr;
                sqlItem.AppendParameter("@workFlowId", workFlowId);
                ClientDBAgent agent = new ClientDBAgent();
                return agent.ExecuteDataTable(sqlItem);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 获取自定义表单数据 
        /// </summary>
        /// <returns></returns>
        public DataTable GetchildFormsType()
        {
            try
            {
                string sqltr = "select * from SysCustomDefineForm";
                SqlDataItem sqlItem = new SqlDataItem();
                sqlItem.CommandText = sqltr;
                ClientDBAgent agent = new ClientDBAgent();
                return agent.ExecuteDataTable(sqlItem);
            }
            catch (Exception ex)
            {
                
                throw ex;
            }
        }
        /// <summary>
        /// 获取数据表 字段名
        /// </summary>
        /// <param name="tableName"></param>
        /// <param name="databaseName"></param>
        /// <returns></returns>
        public DataTable GetDTColumnsNameDataTable(string tableName, string databaseName)
        {
            ClientDBAgent agent=new ClientDBAgent();
            SqlDataItem sqlItem = new SqlDataItem();
            sqlItem.CommandText = "SELECT TableName = OBJECT_NAME(c.object_id), ColumnsName = c.name, ex.value as '字段名' , null as 'ColumnType', Length=c.max_length FROM sys.columns c LEFT OUTER JOIN " +
                                 "sys.extended_properties ex ON ex.major_id = c.object_id AND ex.minor_id = c.column_id AND ex.name = 'MS_Description' " +
                                 "WHERE OBJECTPROPERTY(c.object_id, 'IsMsShipped')=0 AND OBJECT_NAME(c.object_id) =@tableName ";
            sqlItem.DatabaseName = databaseName;
            sqlItem.AppendParameter("@tableName", tableName);
            sqlItem.CommandType = CommandType.Text.ToString();
            return agent.ExecuteDataTable(sqlItem);
        }
        #endregion
        #endregion
    }
}

